import Request from "@/lib/request/index.js"
import {
	refreshTokenFn
} from "@/api/login.js"
import storage from "@/utils/storage.js"
import {
	navigateToLogin,
	clearAllStorage
} from "@/utils/filters.js"
import {
	md5
} from "@/utils/md5.js"
import Foundation from "@/utils/Foundation.js"
import api from "@/config/api.js"
import uuid from "@/utils/uuid.modified.js"
let isNavigateTo = false
let http = new Request()

function cleanStorage() {
	uni.showToast({
		title: "你的登录状态已过期，请重新登录",
		icon: "none",
		duration: 1500,
	})
	if (uni.showLoading()) {
		uni.hideLoading()
	}
	clearAllStorage()
	if (!isNavigateTo) {
		isNavigateTo = true
		navigateToLogin()
	}
}

http.setConfig((config) => {
	// 没有uuid创建
	if (!storage.getUuid()) {
		storage.setUuid(uuid.v1())
	}

	/* 设置全局配置 */
	config.baseURL = api.buyer
	config.header = {
		...config.header,
	}
	config.validateStatus = (statusCode) => {
		// 不论什么状态,统一在正确中处理
		return true
	}
	return config
})

http.interceptors.request.use(
	(config) => {
		/* 请求之前拦截器。可以使用async await 做异步操作 */
		let accessToken = storage.getAccessToken()
		let params = config.params = config.params || {}
		if (accessToken) {
			const nonce = Foundation.randomString(6)
			const timestamp = parseInt(new Date().getTime() / 1000)
			const sign = md5(nonce + timestamp + accessToken)
			const _params = {
				nonce,
				timestamp,
				sign,
			}
			params = {
				...params,
				..._params
			}
			config.params = params
			config.header.accessToken = accessToken
		}
		let choosePosition = storage.getAdCode()
		if (choosePosition) {
			config.params.adCode = choosePosition.chooseCode
		}
		let mapPosition = storage.getMapCode()
		if (mapPosition) {
			config.params.chooseCode = mapPosition.adCode
			config.params.trapeze = mapPosition.trapeze
		}
		if (storage.getTgCode()) {
			config.params.extensionCode = storage.getTgCode()
		}
		config.header = {
			...config.header,
			uuid: storage.getUuid() || uuid.v1(),
		}
		return config
	},
	(config) => {
		return Promise.reject(config)
	}
)
//重试队列
let requests = []
// 必须使用异步函数，注意
http.interceptors.response.use(
	async (response) => {
			isNavigateTo = false
			/* 请求之后拦截器。可以使用async await 做异步操作  */

			let token = storage.getAccessToken()
			if (response.statusCode === 403 || response.data.code === 403) {
				cleanStorage()
				// 如果当前状态码为正常但是success为不正常时
			} else if (
				(response.statusCode == 200 && !response.data.success) || response.statusCode == 400
			) {
				if (response.data.message) {
					uni.showToast({
						title: response.data.message,
						icon: "none",
						duration: 1500,
					})
				}
			}
			return response
		},
		(error) => {
			return error
		}
)

export {
	http
}

export const Method = {
	GET: "GET",
	POST: "POST",
	PUT: "PUT",
	DELETE: "DELETE",
}
